# -*- coding: UTF-8 -*-
__author__ = 'kennyh'
# create time 2018.02.09

# -*-coding:utf-8-*-
import paho.mqtt.client as mqtt
import json
from datetime import datetime as dt_date_time
import time
from logger import logger
from constant import LORAWAN_SERVER, LORAWAN_PORT
import threading
from unpack import UnPackData

LORAWAN_PATROL_T = "lorawan/pub-data"
LORAWAN_SEND_T = "lorawan/send-task"
LORAWAN_RECV_T = "lorawan/recv-task"



class LORAWAN_MQTTClass(object):
    def __init__(self, factory):
        self.factory = factory
        self.lorawan_client = mqtt.Client("lorawan_client")

        # Add message callbacks that will only trigger on a specific subscription match.
        self.lorawan_client.message_callback_add(LORAWAN_PATROL_T, self.on_patrol_message)
        self.lorawan_client.message_callback_add(LORAWAN_RECV_T, self.on_recvback_message)
        self.lorawan_client.on_message = self.on_lorawan_message
        self.lorawan_client.on_connect = self.on_lorawan_connect

        self.lorawan_client.connect(LORAWAN_SERVER, LORAWAN_PORT, 60)

        self.lorawan_client.loop_start()
        self.lorawan_sendlock = threading.RLock()
        logger.info("connect lorawan server %s, port %d" %(LORAWAN_SERVER, LORAWAN_PORT))
        logger.info("lorawan_client init!!!!")

    def on_lorawan_connect(self, mqttc, obj, flags, rc):
        #logger.info("patrol rc: "+str(rc))
        self.lorawan_client.subscribe("lorawan/#", 0)

    def on_lorawan_message(self, mqttc, obj, msg):
        #logger.info(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
        pass

    def on_lorawan_publish(self, mqttc, obj, flags, rc):
        logger.info("send publish: "+str(rc))

    def on_patrol_message(self, mosq, obj, msg):
        logger.info("pub-data: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        result, decode_json = UnPackData.get_json_format(msg.payload)
        if result == False:
            return

        lora_rssi = 0
        lora_snr = 0
        if decode_json.has_key('rssi'):
            lora_rssi = int(decode_json['rssi'])
        if decode_json.has_key('snr'):
            lora_snr = float(decode_json['snr'])
        self.factory.lorawan_save_data(decode_json['node'], decode_json['data'], lora_rssi, lora_snr)

    def on_recvback_message(self, mosq, obj, msg):
        logger.info("recv-task: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        decode_json = json.loads(msg.payload)

    def lorawan_send_cmd(self, addr, msg):

        self.lorawan_sendlock.acquire()
        order_num = dt_date_time.now().strftime('%Y%m%d%H%M%S')
        cmd_dict = {
            "action": "request",
            "order_num": order_num,
            "node": addr,
            "message": msg,
            "send_time": dt_date_time.now().strftime('%Y-%m-%d %H:%M:%S'),
        }

        cmd_msg = json.dumps(cmd_dict)
        logger.info(str(cmd_msg))
        self.lorawan_client.publish(LORAWAN_SEND_T, cmd_msg, qos=2)
        self.lorawan_sendlock.release()

    # If you want to use a specific client id, use
# mqttc = MyMQTTClass("client-id")
# but note that the client id must beprint("publish: "+str(rc)) unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
#mqttc = LORAWAN_MQTTClass()
#mqttc.lorawan_send_cmd("11:8c:94:4b", "0000000080000F000F")
#mqttc.run()

#print "hello world!"

